package com.mlink.ai.chat.ui.activity.chat

import android.text.TextUtils
import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.mlink.ai.chat.AiChatApplication
import com.mlink.ai.chat.bean.ChatRequest
import com.mlink.ai.chat.local.ChatDatabase
import com.mlink.ai.chat.local.entity.ChatMessageEntity
import com.mlink.ai.chat.ui.adapter.ChatItem
import com.mlink.ai.chat.ui.viewmodel.TAG
import kotlinx.coroutines.*
import okhttp3.*
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.sse.EventSource
import okhttp3.sse.EventSourceListener
import okhttp3.sse.EventSources
import java.io.File
import java.io.IOException
import java.util.concurrent.TimeUnit

class ChatViewModelNew : ViewModel() {
    val isOpenData = MutableLiveData<Boolean>()
    val isLoading = MutableLiveData<Boolean>()
    val chatReceiveData = MutableLiveData<String>()
    val errorMsgData = MutableLiveData<String>()

    fun getAnswer() {
        viewModelScope.launch {
            isLoading.postValue(true)
            delay(1000)
            isLoading.postValue(false)
            isOpenData.postValue(true)
            val info = "五千年的风和雨呀，藏了多少梦，黄色的脸，黑色的眼不变是笑容" +
                    "我是齐天大圣孙悟空我会七十二变加筋斗云 如果我爱上你的笑容，" +
                    "要怎么收藏要怎么拥有，如果你快乐不是为我，知足的快乐"
            for (i in 0..50) {
                chatReceiveData.postValue(info[i].toString())
                delay(1000)

            }
            isOpenData.postValue(false)
        }

    }

    fun getAnswer2(role: String, question: String) {
        isLoading.postValue(true)
        val chatRequest = ChatRequest(role, question)
        val chatList = mutableListOf<ChatRequest>()
        chatList.add(chatRequest)
        val mediaType = "application/json".toMediaTypeOrNull()
        val requestBody = Gson().toJson(chatList).toRequestBody(mediaType)
        val url = "http://api.lofty-mount.com:9001/chat_v2"
        val client = OkHttpClient.Builder().connectTimeout(5, TimeUnit.SECONDS)
            .readTimeout(10, TimeUnit.SECONDS)
            .writeTimeout(10, TimeUnit.SECONDS)
            .build()

        val request = Request.Builder()
            .url(url).post(requestBody)
            .addHeader("Accept", "text/event-stream")
            .build()

        EventSources.createFactory(client)
            .newEventSource(request = request, listener = eventSourceListener)
        viewModelScope.launch {
            client.newCall(request).enqueue(responseCallback = object : Callback {
                override fun onFailure(call: Call, e: IOException) {
                    isLoading.postValue(false)
                    errorMsgData.postValue(e.localizedMessage?:"网络异常请重试")
                    Log.e(TAG, "API Call Failure ${e.localizedMessage}")
                }

                override fun onResponse(call: Call, response: Response) {
                    Log.d(TAG, "APi Call Success code: ${response.code}")
                    Log.d(TAG, "APi Call Success ${response.body?.contentLength()}")
                }
            })
        }
    }

    val eventSourceListener = object : EventSourceListener() {
        override fun onOpen(eventSource: EventSource, response: Response) {
            super.onOpen(eventSource, response)
            Log.d(TAG, "Connection Opened")
            isLoading.postValue(false)
            isOpenData.postValue(true)
        }

        override fun onClosed(eventSource: EventSource) {
            super.onClosed(eventSource)
            isOpenData.postValue(false)
            Log.d(TAG, "Connection Closed")
        }

        override fun onEvent(
            eventSource: EventSource,
            id: String?,
            type: String?,
            data: String
        ) {
            super.onEvent(eventSource, id, type, data)
            Log.d(TAG, "On Event Received! Data -: $data")
            val data = Gson().fromJson(data,Delta::class.java)
            chatReceiveData.postValue(data.delta?:"")
        }

        override fun onFailure(eventSource: EventSource, t: Throwable?, response: Response?) {
            isLoading.postValue(false)
            errorMsgData.postValue("网络异常，请重试")
            Log.d(TAG, "On Failure -code: ${response?.code}")
            Log.d(TAG, "On Failure -Throwable: ${t.toString()}")
        }
    }

}

data class Delta(var delta:String?="")